package fms.services.impls;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.logging.Level;
import java.util.logging.Logger;

import fms.common.UserInfo;
import fms.services.ServiceException;
import fms.services.UserService;
import fms.services.impls.tables.TableNameConsts;
import fms.services.impls.tables.UserTableConsts;
import fms.services.persistence.ConnectionFactory;
import fms.services.persistence.ConnectionTool;

public class UserServiceImpl implements UserService{

	
	private Logger log = Logger.getLogger(UserServiceImpl.class.getName());

	private static String ADD_USER_SQL = "INSERT INTO "+TableNameConsts.TABLE_USER+"("
	+UserTableConsts.USER_ID+","
	+UserTableConsts.USER_PASS+","
	+UserTableConsts.USER_NAME+","
	+UserTableConsts.USER_DPMT+","
	+UserTableConsts.USER_SEX+","
	+UserTableConsts.USER_PHONE+","
	+UserTableConsts.USER_ADD+")"
	+ "VALUES(?,?,?,?,?,?,?)";

	public void addUser(UserInfo user) throws ServiceException {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = ConnectionFactory.getFactory().getConnection();
			String sql = ADD_USER_SQL;
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUserID());
			ps.setString(2, user.getUserPass());
			ps.setString(3, user.getUserName());
			ps.setInt(4, user.getUserDpmt());
			ps.setInt(5, user.getUserSex());
			ps.setString(6, user.getUserPhone());
			ps.setString(7, user.getUserAdd());
			
			ps.execute();
			System.out.println("add ends here");
		} catch (Exception ex) {
			log.log(Level.SEVERE, "add user failed! " + user.getUserID());
			ex.printStackTrace();
			throw new ServiceException(
					ServiceException.SERVICE_EXCUTING_EXCEPTION_DBERROR,
					"add user failed!");

		} finally {
			ConnectionTool.closeConnection(conn, ps, null);
		}
		
	}

	public void updateUser(UserInfo user) throws ServiceException {
		// TODO Auto-generated method stub
		
	}

	public void deleteUser(UserInfo user) throws ServiceException {
		// TODO Auto-generated method stub
		
	}
	
	public String getServiceName() {
		return "User Service Implementation";
	}

	public String getServiceVersion() {
		return "1.0";
	}
	
	public static void main(String[] args) {
		UserServiceImpl us = new UserServiceImpl();
		UserInfo userInfo = new UserInfo();
		userInfo.setUserAdd("address");
		userInfo.setUserDpmt(1);
		userInfo.setUserID("jessiena");
		userInfo.setUserName("wangrui");
		userInfo.setUserPass("123456");
		userInfo.setUserPhone("11331313131");
		userInfo.setUserSex(1);
		try {
			us.addUser(userInfo);
		} catch (ServiceException e) {
			System.out.println("add user failed!");
			e.printStackTrace();
		}

	}
	
	

}
